var comment = require("../models/comment");
var Category = require("../models/category");
var laypage=require("laypage");

//评价列表
exports.list = function (req, res) {
	var pageSize = 10; //每页显示条数
	var page = req.params.num - 1 || 0;
	var _id = req.query.id
    comment.find({cid:_id}).count().exec(function (err, sum) {
        comment.find({cid:_id}).limit(pageSize).skip(pageSize * page).sort({_id: -1}).exec(function (err, _comment) {
			res.render('admin/commentList', {
				title: '评价列表',
				laypage: laypage({
					curr: req.params.num || 1,
					url: req.url, //必传参数，获取当前页的url
					groups: 5,
					pages: Math.ceil(sum/pageSize), //分页总数你需要通过sql查询得到
					prev: '‹',
					next: '›'
				}),
                 cid:_id,
                 commentList:_comment,
				pagesize: sum
			})
		});
	});
}

//项目案例
exports.add = function (req, res) {
	var _id = req.query.id;
	res.render('admin/commentAdd', {
		title: '添加案例',
         cid:_id
	})
}

exports.update = function (req, res) {
	var _comment = req.params,
		_id = req.query.id;
        comment.findOne({
			"_id": _comment.id
		}, function (err, $comment) {
			res.render('admin/commentUpdate', {
				title: '编辑案例',
                 comment: $comment,
				cid:_id
			})
		});
}

//内容提交与更新
exports.save = function (req, res) {
	var commentC = req.body,
		_id = commentC.cid,
		_commentC = {
			name: commentC.name,
			id: commentC.id,
			cid:_id,
            addData:commentC.addData,
			avatar: commentC.avatar,
			content:commentC.content
		 }

	if (commentC._id) {
		var id = commentC._id;
		comment.update({
			_id: id
		}, _commentC, function (err) {
			res.redirect("/admin/commentList?id="+_id);
		});
	} else {
        comment.create(_commentC, function (err) {
			res.redirect("/admin/commentList?id="+_id);
		});
	}

}

//单个删除
exports.delete = function (req, res) {
	var id = req.params.id,
		_id = req.query.id;
    comment.remove({_id:id}, function (err) {
    	    if(err){
    	    	  console.log(err)
		}
        res.redirect("/admin/commentList?id="+_id);
	})
}